//
//  iFoundItAppDelegate.m
//  iFoundIt
//
//  Created by Navid Shariat on 4/05/10.
//  Copyright QUT 2010. All rights reserved.
//

#import "iFoundItAppDelegate.h"
#import "StorePersistentManager.h"

@implementation iFoundItAppDelegate

@synthesize window;
@synthesize tabBarController;

static NSString * dbname=@"ifoundit.sqlite";

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    
    // Add the tab bar controller's current view as a subview of the window
	[self copyDatabaseIfNeeded];
    [window addSubview:tabBarController.view];
}


/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
}
*/

/*
// Optional UITabBarControllerDelegate method
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed {
}
*/


- (void)dealloc {
    [tabBarController release];
    [window release];
    [super dealloc];
}

- (NSString *) getDBPath {
	
	//Search for standard documents using NSSearchPathForDirectoriesInDomains
	//First Param = Searching the documents directory
	//Second Param = Searching the Users directory and not the System
	//Expand any tildes and identify home directories.
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	//	return [documentsDir stringByAppendingPathComponent:@"iFoundit.sqlite"];
	return [documentsDir stringByAppendingPathComponent:dbname];
	
}

- (void) copyDatabaseIfNeeded {
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [self getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath];
	
	if(!success) {
			
		//		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		NSLog(@"DB Copied!");
		if (!success)
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
//		[defaultDBPath release];		
	}
	 //fileManager release];
	}

- (void) copyDatabase {
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [self getDBPath];
	NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
	BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];		
	if (!success)
		NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

@end

